package recipes

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"path/filepath"
	"savor_gin/controllers"
	. "savor_gin/errorType"
	"savor_gin/models"
	. "savor_gin/utils/token"
	"strconv"
)

// 上传食谱信息
func AddRecipe(c *gin.Context) {
	if contextData, exists := c.Get("contextData"); exists {
		if data, ok := contextData.(*TokenContext); ok {
			id := data.Id
			var form models.FormData
			if err := c.ShouldBind(&form); err != nil {
				controllers.SendResp(c, ParamBindError, nil)
				return
			}
			fileHeader, err := c.FormFile("file")
			if err != nil {
				controllers.SendResp(c, ParamBindError, nil)
				return
			}
			dirPath := "D:/Xampp/htdocs/savor/"
			if _, err := os.Stat(dirPath); os.IsNotExist(err) {
				if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
					fmt.Println("Failed to create directory:", err)
					controllers.SendResp(c, InternalServerError, nil)
					return
				}
			}
			fileName := filepath.Base(fileHeader.Filename)
			filePath := filepath.Join(dirPath, fileName)
			dst, err := os.Create(filePath)
			if err != nil {
				fmt.Println("Failed to create file:", err)
				controllers.SendResp(c, InternalServerError, nil)
				return
			}
			defer dst.Close()
			src, err := fileHeader.Open()
			if err != nil {
				fmt.Println("Failed to open file:", err)
				controllers.SendResp(c, PicPutError, nil)
				return
			}
			defer src.Close()
			if _, err := io.Copy(dst, src); err != nil {
				fmt.Println("Failed to save file:", err)
				controllers.SendResp(c, PicPutError, nil)
				return
			}
			imageURL := fmt.Sprintf("http://127.0.0.1:8088/savor/%s", fileName)
			recipe := models.Recipes{
				UserID:       id,
				Title:        form.Title,
				Description:  form.Description,
				Ingredients:  form.Ingredients,
				Instructions: form.Instructions,
				ImageURL:     imageURL,
			}
			if err := recipe.Create(); err != nil {
				controllers.SendResp(c, DataBaseError, nil)
				return
			}
			controllers.SendResp(c, OK, recipe)
		}
	} else {
		controllers.SendResp(c, TokenTimeOverError, nil)
		return
	}
}

// 更新食谱信息
func UpdateRecipeInfo(c *gin.Context) {
	recipeId, err := strconv.Atoi(c.Param("recipeId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	s := &models.Recipes{RecipeID: uint64(recipeId)}
	if err := c.ShouldBind(s); err != nil {
		controllers.SendResp(c, ParamBind2Error, err)
		return
	}
	if err := s.Update(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	}
	controllers.SendResp(c, OK, s)
}

// 删除食谱信息
func DeleteRecipe(c *gin.Context) {
	// 通过动态URL传递参数
	recipeId, err := strconv.Atoi(c.Query("recipeId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	s := &models.Recipes{RecipeID: uint64(recipeId)}
	if err := s.Delete(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	}
	controllers.SendResp(c, OK, nil)
}

// 根据id获取食谱信息
func GetRecipeById(c *gin.Context) {
	recipeId, err := strconv.Atoi(c.Query("recipeId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	var recipe models.Recipes
	recipe.RecipeID = uint64(recipeId)
	if err := recipe.GetRecipesById(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	}
	controllers.SendResp(c, OK, recipe)
}

// 查询个人食谱
func GetRecipeListByUserId(c *gin.Context) {
	if contextData, exists := c.Get("contextData"); exists {
		if data, ok := contextData.(*TokenContext); ok {
			userId := data.Id
			if s, err := models.GetRecipeByUserId(userId); err != nil {
				controllers.SendResp(c, DataBaseError, err)
				return
			} else {
				controllers.SendResp(c, OK, s)
			}
		} else {
			controllers.SendResp(c, TokenTimeOverError, nil)
			return
		}
	}
}

// 查询食谱列表
func GetRecipeList(c *gin.Context) {
	if s, err := models.GetRecipe(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}

// 模糊查询食谱列表
func GetRecipeListLikeKey(c *gin.Context) {
	keyword := c.Query("keyword")
	if keyword == "undefined" {
		if s, err := models.GetRecipeLimit(); err != nil {
			controllers.SendResp(c, DataBaseError, err)
			return
		} else {
			controllers.SendResp(c, OK, s)
			return
		}
	}
	if s, err := models.GetRecipeByLike(keyword); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}
